﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace WebApplication1
{
    public class SqlHelper
    {
        private string constr = "server=.;uid=sa;pwd=123456;database=Student_db";

        private SqlConnection cot=null;
        public SqlHelper()
        {
             cot = new SqlConnection(constr);
        }
        public DataTable Get(string sql,SqlParameter [] sqls) 
        {
            try
            {
                if (cot.State==ConnectionState.Closed)
                {
                    cot.Open();
                }
                SqlCommand cmd = new SqlCommand(sql,cot);
                if (sqls != null)
                {
                    cmd.Parameters.AddRange(sqls);
                }
                SqlDataAdapter sdat = new SqlDataAdapter(cmd);
                DataSet data = new DataSet();
                sdat.Fill(data);
                return data.Tables[0];
            }
            catch (Exception e)
            {
                throw new Exception(e.Message.ToString());
            }
            finally 
            {
                if (cot!=null)
                {
                    cot.Close();
                }
            }
        }

        public bool Execute(string sql ,SqlParameter[] sqls) 
        {
            try
            {
                if (cot.State == ConnectionState.Closed)
                {
                    cot.Open();
                }
                SqlCommand cmd = new SqlCommand(sql,cot);
                if (sqls != null)
                {
                    cmd.Parameters.AddRange(sqls);
                }

                return cmd.ExecuteNonQuery() > 0 ? true : false;
            }
            catch (Exception e)
            {

                throw new Exception(e.Message.ToString());
            }
            finally 
            {
                if (cot!=null)
                {
                    cot.Close();
                }
            }
        }
    }
}